import machine
import ubinascii
import dht

# 设备ID
CLIENT_ID = ubinascii.hexlify(machine.unique_id()).decode("utf-8")
# MQTT 主题路径
TOPIC_T = "device/dht11_T/{}".format(CLIENT_ID)
TOPIC_T = TOPIC_T.encode()
TOPIC_H = "device/dht11_H/{}".format(CLIENT_ID)
TOPIC_H = TOPIC_H.encode()
temp_client = None
# 初始化DHT11传感器
sensor = dht.DHT11(machine.Pin(27))


def dht11_callback(t):
    sensor.measure()  # 测量温湿度值
    temp = sensor.temperature()  # 温度，单位摄氏度
    hum = sensor.humidity()  # 湿度，单位百分比
    print("空气温度：", temp)
    print("空气湿度：", hum)
    temp_client.publish(TOPIC_T, str(temp))
    temp_client.publish(TOPIC_H, str(hum))
    return {"temp": temp, "hum": hum}


def register_dht11_topic(client):
    global temp_client
    temp_client = client
    # temp_client.subscribe(TOPIC_T)
    # temp_client.subscribe(TOPIC_H)
    # 安排温度读取的定时器，每1min执行一次
    # temp_timer = machine.Timer(1)
    # temp_timer.init(period=60000, mode=machine.Timer.PERIODIC, callback=dht11_callback)
